// Client

AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

// Include

include('shared.lua')

// Initialize

function ENT:Initialize()
	self.Entity:PhysicsInit(SOLID_VPHYSICS)
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
	self.Entity:SetSolid(SOLID_VPHYSICS)
	self.Entity:SetUseType(ONOFF_USE)
	self.Entity:SetNetworkedInt(0, 0)
	
	local Bool = false
	
	if (self.Entity.Inversed == 1) then
		Bool = true
	end
	
	self:SetEntityPressing(Bool)
	
	if (Wire_CreateOutputs) then
		self.Outputs = Wire_CreateOutputs(self.Entity, {"Active"})
	end
	
	if (Wire_TriggerOutput) then
		Wire_TriggerOutput(self.Entity, "Active", self.Entity.Inversed)
	end
end

// Think

function ENT:Think()
	local Trace = {}
	
	Trace.start = self.Entity:GetPos()
	Trace.endpos = self.Entity:GetPos() + (self.Entity:GetUp() * self:GetEntityLength())
	Trace.filter = self.Entity
	
	if (self.Entity.Water == 1) then
		Trace.mask = MASK_WATER
	end

	local TR = util.TraceLine(Trace) 
 
	if (self.Entity.Inversed == 0) then
		if (TR.Hit) then
			if not (self:IsEntityPressing()) then
				self:EntityToggle(true)
			end
		else
			if (self:IsEntityPressing()) then
				self:EntityToggle(false)
			end
		end
	else
		if (TR.Hit) then
			if (self:IsEntityPressing()) then
				self:EntityToggle(false)
			end
		else
			if not (self:IsEntityPressing()) then
				self:EntityToggle(true)
			end
		end
	end
	
	self:SetEntityLabel(self.Entity.Description)
end

// When entity is removed

function ENT:OnRemove()
	local Player = self:GetEntityPlayer()
	local Index  = self:GetEntityIndex()
	local Key 	 = self:GetEntityKey()
	
	numpad.Deactivate(Player, _, {Key}, Index)
end

// Toggle the entity

function ENT:EntityToggle(Bool)
	local Player = self:GetEntityPlayer()
	local Index  = self:GetEntityIndex()
	local Key 	 = self:GetEntityKey()
	
	if (Bool) then
		numpad.Activate(Player, _, {Key}, Index)
		
		if (self.Entity.Once == 1) then
			numpad.Deactivate(Player, _, {Key}, Index)
		end
		
		self:SetEntityPressing(true)
	else
		if (self.Entity.Once == 1) then
			numpad.Activate(Player, _, {Key}, Index)
		end
		
		numpad.Deactivate(Player, _, {Key}, Index)
		
		self:SetEntityPressing(false)
	end
	
	local Number = 0
	
	if (Bool) then
		Number = 1
	end
	
	if (Wire_TriggerOutput) then
		Wire_TriggerOutput(self.Entity, "Active", Number)
	end
end